package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowData;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowProperties;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowResponse;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.page.PageDomain;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.DeviceDataListDto;
import com.zzyl.nursing.dto.FamilyElderDto;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.vo.DeviceDataListVo;
import com.zzyl.nursing.vo.ElderBedDeviceVo;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 老人家属Service业务层处理
 *
 * @author mr.wu
 * @date 2025-05-23
 */
@Service
public class FamilyMemberElderServiceImpl extends ServiceImpl<FamilyMemberElderMapper, FamilyMemberElder> implements IFamilyMemberElderService {
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private ElderServiceImpl elderService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private IFamilyMemberService familyMemberService;

    /**
     * 绑定家人
     *
     * @param dto
     */
    @Override
    public void familyElderadd(String token, FamilyElderDto dto) {

        Claims claims = tokenService.parseToken(token);// 解析 token 获取 openid
//2. 根据openId查询用户数据
        FamilyMember member = familyMemberService.lambdaQuery().eq(FamilyMember::getId, claims.get("userId")).one();
        Elder elder = elderService.lambdaQuery()
                .eq(StringUtils.isNotBlank(dto.getIdCard()), Elder::getIdCardNo, dto.getIdCard())
                .like(StringUtils.isNotBlank(dto.getName()), Elder::getName, dto.getName())
                .one();
        if (null != elder) {
            FamilyMemberElder familyMemberElder = new FamilyMemberElder();
            familyMemberElder.setElderId(elder.getId());
            familyMemberElder.setRemark(dto.getRemark());
            familyMemberElder.setFamilyMemberId(member.getId());
            familyMemberElder.setCreateBy(String.valueOf(member.getId()));
            familyMemberElder.setCreateTime(LocalDateTime.now());
            familyMemberElderMapper.familyElderadd(familyMemberElder);
        } else {
            throw new BaseException("插入的家属老人为空");
        }
    }

    /**
     * 根据id解绑数据
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        familyMemberElderMapper.deleteById(id);
    }

    /**
     * 查询加入列表
     *
     * @return
     */
    @Override
    public List<FamilyMemberElderVo> familyElderMy() {
        List<FamilyMemberElderVo> familyMemberElderVoList = familyMemberElderMapper.familyElderMy();
        return familyMemberElderVoList;
    }

    /**
     * 查看家人列表（分页查询）
     *
     * @param pageDomain
     * @return
     */
    @Override
    public List<ElderBedDeviceVo> familyElderpage(String token, PageDomain pageDomain) {
        Claims claims = tokenService.parseToken(token);// 解析 token 获取 openid
        Long userId = familyMemberService.lambdaQuery().eq(FamilyMember::getId, claims.get("userId")).one().getId();
        pageDomain.setPageNum(pageDomain.getPageNum() - 1);
        List<ElderBedDeviceVo> elderBedDeviceVoList = familyMemberElderMapper.familyElderpage(pageDomain, userId);
        return elderBedDeviceVoList;
    }

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IoTDAClient client;

    /**
     * 查询健康数据
     *
     * @param deviceName
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult QueryDevicePropertyStatus(String deviceName, String productKey) {
        //1. 判断设备是否存在
        Device device = deviceService.lambdaQuery().eq(Device::getDeviceName, deviceName).select(Device::getIotId).one();
        if(device==null) {
            throw new BaseException("设备不存在");
        }
        String deviceId = device.getIotId();//获取设备id

        //2. 调用华为云IOT接口查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(deviceId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if(response==null || response.getHttpStatusCode()!=200) {
            throw new BaseException("调用华为云IOT接口查询设备影子数据失败");
        }

        //3. 解析响应结果数据，封装map的数据
        List<DeviceShadowData> shadowDataList = response.getShadow();
        if(CollUtil.isEmpty(shadowDataList)) {
            throw new BaseException("调用华为云IOT接口查询设备影子数据为空");
        }
        DeviceShadowData shadowData = shadowDataList.get(0);
        DeviceShadowProperties reported = shadowData.getReported();
        //事件操作时间，格式：yyyyMMdd'T'HHmmss'Z'，如20151212T121212Z。该值是国际标准时间，比东八区早八小时
        String eventTimeStr = reported.getEventTime();//数据上报时间
        //转为东八区时间
       // LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
        //        .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
           //     .toLocalDateTime();


        // 解析时间字符串为 OffsetDateTime
        long eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX")).toInstant().toEpochMilli();

        JSONObject properties = JSONUtil.parseObj(reported.getProperties());
        List<Map<String,Object>> propertyStatusInfo = new ArrayList<>();
        properties.forEach((k,v)->{
            //封装属性对象
            Map<String,Object> propertyMap = new HashMap<>();
            if (k.equals("xueyang")) {
                propertyMap.put("dataType","int");
                propertyMap.put("identifier",k);
                propertyMap.put("name","血氧");
                propertyMap.put("value",v.toString());
                propertyMap.put("unit ","次/分");
                propertyMap.put("time",eventTime);
                propertyStatusInfo.add(propertyMap);
            }else if (k.equals("BodyTemp")) {
                propertyMap.put("dataType","float");
                propertyMap.put("identifier",k);
                propertyMap.put("name","温度");
                propertyMap.put("value",v.toString());
                propertyMap.put("unit ","°C");
                propertyMap.put("time",eventTime);
                propertyStatusInfo.add(propertyMap);
            }else if (k.equals("BatteryPercentage")) {
                propertyMap.put("dataType","double");
                propertyMap.put("identifier",k);
                propertyMap.put("name","用电量");
                propertyMap.put("value",v.toString());
                propertyMap.put("unit ","%");
                propertyMap.put("time",eventTime);
                propertyStatusInfo.add(propertyMap);
            }else if (k.equals("HeartRate")) {
                propertyMap.put("dataType","int");
                propertyMap.put("identifier",k);
                propertyMap.put("name","心率");
                propertyMap.put("value",v.toString());
                propertyMap.put("time",eventTime);
                propertyStatusInfo.add(propertyMap);
            }
        });


// 定义排序字段的顺序
        List<String> orderKeys = Arrays.asList("xueyang", "BodyTemp", "BatteryPercentage", "HeartRate");

// 排序
        propertyStatusInfo.sort(Comparator.comparingInt(p -> orderKeys.indexOf((String) p.get("identifier"))));

        //4. 返回Map数据
        Map<String,Object> resultMap = new HashMap<>();

        Map<String,Object> propertyStatusInfoMap = new HashMap<>();
        propertyStatusInfoMap.put("propertyStatusInfo", propertyStatusInfo);

        resultMap.put("list",propertyStatusInfoMap);

        return  AjaxResult.success(resultMap);
    }

    /**
     * 按天统计查询指标数据
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult queryDeviceDataListByDay(DeviceDataListDto dto) {

        dto.setBeginTime(LocalDateTime.ofInstant(
                Instant.ofEpochMilli(dto.getStartTime()),
                ZoneId.systemDefault()
        ));

        dto.setStopTime(LocalDateTime.ofInstant(
                Instant.ofEpochMilli(dto.getEndTime()),
                ZoneId.systemDefault()
        ));
        List<DeviceDataListVo> deviceDataListVos = familyMemberElderMapper.queryDeviceDataListByDay(dto);
        return AjaxResult.success(deviceDataListVos);
    }
    /**
     * 按天统计查询指标数据
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult queryDeviceDataListByWeek(DeviceDataListDto dto) {

        dto.setBeginTime(LocalDateTime.ofInstant(
                Instant.ofEpochMilli(dto.getStartTime()),
                ZoneId.systemDefault()
        ));

        dto.setStopTime(LocalDateTime.ofInstant(
                Instant.ofEpochMilli(dto.getEndTime()),
                ZoneId.systemDefault()
        ));
        List<DeviceDataListVo> deviceDataListVos = familyMemberElderMapper.queryDeviceDataListByWeek(dto);
        return AjaxResult.success(deviceDataListVos);
    }
}
